
import ReactDOM from 'react-dom'
const state = []
const setters = []
let stateIndex = 0

const createSetter = index => {
    return function(newValue) {
        state[index] = newValue
        render()
    }
}

const useState = (initState) => {
    if (state[stateIndex] === undefined) state[stateIndex] = initState

    if (!setters[stateIndex]) {
        setters[stateIndex] = createSetter(stateIndex)
    }
    const currentState = state[stateIndex]
    const setter = setters[stateIndex]
    stateIndex++
    return [ currentState, setter]
}

const render = () => {
    stateIndex = 0
    ReactDOM.render(<HelloWorld />, document.querySelector('#app'))
}


const HelloWorld = () => {
    const [count, setCount] = useState(0)
    const [name, setName] = useState('jack')
    return (
        <div>
            <p>{count}</p>
            <button onClick={() => setCount(count + 1)}>+ 1</button>
            <p>{name}</p>
            <button onClick={() => setName('nini')}>+ 1</button>
        </div>
    )
}

export default HelloWorld